package com.employee.servlet;

import com.employee.dao.AccountDao;
import com.employee.entity.Account;
import com.google.gson.Gson;
import com.employee.util.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    private AccountDao accountDao = new AccountDao();
    private Gson gson = new Gson();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        PrintWriter out = response.getWriter();
        
        if (username == null || username.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("用户名不能为空")));
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("密码不能为空")));
            return;
        }
        
        try {
            Account account = accountDao.findByUsername(username.trim());
            
            if (account == null) {
                out.print(gson.toJson(JsonResult.error("用户名不存在")));
                return;
            }
            
            if (!password.equals(account.getPassword())) {
                out.print(gson.toJson(JsonResult.error("密码错误")));
                return;
            }
            
            accountDao.updateLastLoginTime(username, new Date());
            
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            session.setAttribute("userId", account.getId());
            
            out.print(gson.toJson(JsonResult.success("登录成功")));
            
        } catch (Exception e) {
            e.printStackTrace();
            out.print(gson.toJson(JsonResult.error("系统错误")));
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
}
